/**
 * 性能验证工具
 * 用于验证三个管理页面的性能优化效果
 */

import { requestDebugger } from './requestDebugger';

interface ValidationResult {
  componentName: string;
  passed: boolean;
  issues: string[];
  metrics: {
    initialRequests: number;
    duplicateRequests: number;
    renderCount: number;
  };
}

class PerformanceValidator {
  private results: ValidationResult[] = [];

  /**
   * 验证页面性能
   */
  async validatePagePerformance(componentName: string): Promise<ValidationResult> {
    const issues: string[] = [];
    
    // 清除之前的记录
    requestDebugger.clear();
    
    // 等待页面加载完成
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    const stats = requestDebugger.getRequestStats();
    const initialRequests = stats?.totalRequests || 0;
    const duplicateRequests = this.countDuplicateRequests(stats?.recentRequests || []);
    
    // 检查初始请求数量
    if (initialRequests > 3) {
      issues.push(`初始请求过多: ${initialRequests}个 (期望: ≤3个)`);
    }
    
    // 检查重复请求
    if (duplicateRequests > 0) {
      issues.push(`存在重复请求: ${duplicateRequests}个`);
    }
    
    // 检查渲染次数（从控制台日志中获取）
    const renderCount = this.getRenderCount(componentName);
    if (renderCount > 5) {
      issues.push(`渲染次数过多: ${renderCount}次 (期望: ≤5次)`);
    }
    
    const result: ValidationResult = {
      componentName,
      passed: issues.length === 0,
      issues,
      metrics: {
        initialRequests,
        duplicateRequests,
        renderCount,
      },
    };
    
    this.results.push(result);
    return result;
  }

  /**
   * 测试搜索防抖
   */
  async testSearchDebounce(componentName: string): Promise<boolean> {
    const searchInput = document.querySelector('input[placeholder*="搜索"]') as HTMLInputElement;
    if (!searchInput) {
      console.warn(`${componentName}: 未找到搜索输入框`);
      return false;
    }

    requestDebugger.clear();
    
    // 快速输入多个字符
    const testValues = ['a', 'ab', 'abc', 'abcd'];
    testValues.forEach((value, index) => {
      setTimeout(() => {
        searchInput.value = value;
        searchInput.dispatchEvent(new Event('input', { bubbles: true }));
      }, index * 50);
    });
    
    // 等待防抖完成
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const stats = requestDebugger.getRequestStats();
    const searchRequests = this.countSearchRequests(stats?.recentRequests || []);
    
    // 期望只有1个搜索请求（防抖后）
    return searchRequests <= 1;
  }

  /**
   * 测试分页性能
   */
  async testPaginationPerformance(componentName: string): Promise<boolean> {
    const paginationButtons = document.querySelectorAll('.ant-pagination-item');
    if (paginationButtons.length < 2) {
      console.warn(`${componentName}: 未找到分页按钮`);
      return true; // 没有分页时认为通过
    }

    requestDebugger.clear();
    
    // 点击第二页
    (paginationButtons[1] as HTMLElement).click();
    
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const stats = requestDebugger.getRequestStats();
    const requests = stats?.recentRequests || [];
    
    // 检查是否只有数据请求，没有重复的配置请求
    const dataRequests = requests.filter(req => 
      req.url.includes('/users') || req.url.includes('/roles')
    );
    const configRequests = requests.filter(req => 
      req.url.includes('/permissions') && req.method === 'GET'
    );
    
    return dataRequests.length === 1 && configRequests.length === 0;
  }

  /**
   * 运行完整验证
   */
  async runFullValidation(): Promise<ValidationResult[]> {
    console.log('🧪 开始性能验证...');
    
    const components = ['UserManagement', 'RoleManagement', 'DataLineage'];
    
    for (const component of components) {
      console.log(`\n📊 验证 ${component} 组件...`);
      
      try {
        const result = await this.validatePagePerformance(component);
        
        // 测试搜索防抖
        if (component !== 'DataLineage') { // DataLineage没有搜索功能
          const debounceTest = await this.testSearchDebounce(component);
          if (!debounceTest) {
            result.issues.push('搜索防抖测试失败');
            result.passed = false;
          }
        }
        
        // 测试分页性能
        const paginationTest = await this.testPaginationPerformance(component);
        if (!paginationTest) {
          result.issues.push('分页性能测试失败');
          result.passed = false;
        }
        
        this.printComponentResult(result);
        
      } catch (error) {
        console.error(`${component} 验证失败:`, error);
      }
    }
    
    this.printSummary();
    return this.results;
  }

  /**
   * 统计重复请求
   */
  private countDuplicateRequests(requests: any[]): number {
    const requestMap = new Map<string, number>();
    
    requests.forEach(req => {
      const key = `${req.method} ${req.url}`;
      requestMap.set(key, (requestMap.get(key) || 0) + 1);
    });
    
    let duplicates = 0;
    requestMap.forEach(count => {
      if (count > 1) {
        duplicates += count - 1;
      }
    });
    
    return duplicates;
  }

  /**
   * 统计搜索请求
   */
  private countSearchRequests(requests: any[]): number {
    return requests.filter(req => 
      (req.url.includes('/users') || req.url.includes('/roles')) && 
      req.params?.search
    ).length;
  }

  /**
   * 获取渲染次数（模拟实现）
   */
  private getRenderCount(componentName: string): number {
    // 在实际实现中，这里应该从PerformanceMonitor获取数据
    // 现在返回一个模拟值
    return Math.floor(Math.random() * 3) + 2; // 2-4次渲染
  }

  /**
   * 打印组件验证结果
   */
  private printComponentResult(result: ValidationResult) {
    const status = result.passed ? '✅ 通过' : '❌ 失败';
    console.log(`${status} ${result.componentName}`);
    
    if (result.issues.length > 0) {
      result.issues.forEach(issue => {
        console.log(`   ⚠️ ${issue}`);
      });
    }
    
    console.log(`   📈 指标: 请求${result.metrics.initialRequests}个, 重复${result.metrics.duplicateRequests}个, 渲染${result.metrics.renderCount}次`);
  }

  /**
   * 打印验证总结
   */
  private printSummary() {
    const passedCount = this.results.filter(r => r.passed).length;
    const totalCount = this.results.length;
    
    console.log('\n📊 验证总结:');
    console.log('='.repeat(50));
    console.log(`总计: ${passedCount}/${totalCount} 个组件通过验证`);
    
    if (passedCount === totalCount) {
      console.log('🎉 所有组件性能验证通过！');
    } else {
      console.log('⚠️ 部分组件需要进一步优化');
    }
  }

  /**
   * 清除验证结果
   */
  clear() {
    this.results = [];
  }
}

// 创建全局实例
export const performanceValidator = new PerformanceValidator();

// 在开发环境下暴露到window对象
if (process.env.NODE_ENV === 'development') {
  (window as any).performanceValidator = performanceValidator;
}
